/* eslint-disable @typescript-eslint/no-shadow */
import { observer, useLocalObservable } from 'mobx-react'
import styles from './index.module.less'
import Store from '../store'
import { useEffect, useRef, useState } from 'react'
import { SocketContainer } from '@/hooks/useSocket'
import btn_chengjiao_n from '@/resource/auctionManage/btn_chengjiao_n.png'
import btn_chengjiao_s from '@/resource/auctionManage/btn_chengjiao_s.png'
import default_avatar from '@/resource/default_avatar.png'
import btn_over_n from '@/resource/auctionManage/btn_over_n.png'
import btn_over_s from '@/resource/auctionManage/btn_over_s.png'
import gold from '@/resource/auctionManage/gold.png'
import silver from '@/resource/auctionManage/silver.png'
import copper from '@/resource/auctionManage/copper.png'
import HoverImage from '../components/HoverImg'
import AnimationList from '../components/AnimationList'
import { compareArrays } from '../components/AnimationList/utils'
import { useResize } from '@/hooks/useResize'

let topIndex = 0
const sortNum = '0①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿'
export default observer(() => {
    const store = useLocalObservable(() => Store)
    const { binding_info, setData, lot_obj, initBindingInfo } = store
    const { send, onMessage, remove } = SocketContainer.useContainer()
    const [success, setSuccess] = useState(false)
    const { binding_result } = binding_info || {}
    const oldRsult = useRef([])
    const lotObjRef = useRef(lot_obj)
    const bindingInfoRef = useRef(binding_info)
    const audioRef = useRef<any>(null)
    const [topData, setTopData] = useState<any>([])
    useResize({ id: 'resize_container', needHeight: true })

    useEffect(() => {
        oldRsult.current = binding_result
    }, [binding_result])

    useEffect(() => {
        lotObjRef.current = lot_obj
    }, [lot_obj])

    useEffect(() => {
        bindingInfoRef.current = binding_info
    }, [binding_info])

    useEffect(() => {
        document.title = '拍卖游戏'
        /** 竞价 */
        function bidding({ data }: any) {
            const { bidding_result: newResult, bidding_price_avg, bidding_student_num, is_pass, lot_id } = data
            /** 排名数据 */
            const result = compareArrays(
                oldRsult?.current,
                newResult.map((item: any) => ({ ...item, height: 60 })),
                'user_id',
            )
            result.forEach((item, index) => {
                setTimeout(() => {
                    if (lot_id && lotObjRef?.current?.id !== lot_id) {
                        return
                    }
                    setData('binding_info', {
                        ...binding_info,
                        binding_result: item,
                        bidding_price_avg,
                        bidding_student_num,
                    })
                }, 0)
                setTimeout(() => {
                    const deal_item = item.filter(item => !!item.price)
                    console.log('deal_item', deal_item)
                    if (lot_id && lotObjRef?.current?.id !== lot_id) {
                        return
                    }
                    /** pass 的逻辑 */
                    if (is_pass === '1') {
                        return
                    }
                    setTopData(v => {
                        if (v.length === 0) {
                            return [{}]
                        }
                        return index === 0
                            ? [
                                  { user_id: new Date().valueOf(), height: 78 },
                                  { ...deal_item[0], height: 78, user_id: `s${topIndex}` },
                                  { ...deal_item[deal_item.length - 1], height: 78, user_id: `s${topIndex + 1}` },
                              ]
                            : [
                                  { ...deal_item[deal_item.length - 1], height: 78, user_id: `s${topIndex - 1}` },
                                  { ...deal_item[0], height: 78, user_id: `s${topIndex}` },
                                  { user_id: new Date().valueOf(), height: 78 },
                              ]
                    })
                    topIndex = topIndex + 1
                }, index * 100)
            })

            /** 牌子数据 */
        }

        /** 切换下一件商品 */
        function step_flow({ data }: any) {
            if (data.goto === 'game') {
                setTimeout(() => {
                    setSuccess(false)
                }, 800)
                initBindingInfo()
                setTopData([])
            }
        }

        /** 断连 */
        function close({ data }: any) {
            const { bidding_student_num } = data || {}
            setData('binding_info', {
                ...bindingInfoRef.current,
                bidding_student_num,
            })
        }

        /** 学生进入游戏 */
        function connect({ data }: any) {
            const { connect_inc_num = 0, bidding_student_num } = data || {}
            console.log(connect_inc_num)
            setData('binding_info', {
                ...bindingInfoRef.current,
                bidding_student_num,
            })
        }

        /** 竞价 */
        onMessage('bidding', bidding)
        /** 断连 */
        onMessage('close', close)
        /** 切换下一件商品 */
        onMessage('step_flow', step_flow)
        /** 学生进入游戏 */
        onMessage('connect', connect)
        return () => {
            remove('bidding', bidding)
            remove('step_flow', step_flow)
            remove('close', close)
            remove('connect', connect)
        }
    }, [])
    console.log(binding_info?.bidding_student_num)
    return (
        <div className={styles.container}>
            <div id="resize_container">
                <div className={styles.top_hang}>
                    {/* <AnimationRotateX active={binding_result?.[0]?.price}> */}
                    <div className={styles.top_hang_warpper}>
                        <AnimationList classWrapper={styles.animated_wrapper} data={topData}>
                            {(item: any) => {
                                return (
                                    <div className={styles.hang_wrapper}>
                                        <div className={styles.avatar_warpper}>
                                            <img src={item?.avatar || default_avatar} />
                                        </div>
                                        <div className={styles.info}>
                                            <span>{item?.name || '--'}</span>
                                            <span className={styles.tips}>参与竞价</span>
                                        </div>
                                        <div className={styles.price}>{item?.price || '--'}万</div>
                                    </div>
                                )
                            }}
                        </AnimationList>
                    </div>
                    {/* </AnimationRotateX> */}
                </div>
                <div className={styles.stage_container}>
                    <div className={styles.scoreboard}>
                        <div className={styles.scoreboard_wrapper}>
                            <div className={styles.average}>平均竞价金额：{binding_info?.bidding_price_avg} 万</div>
                            <div className={styles.animation_wrapper}>
                                <AnimationList data={binding_result}>
                                    {(item: any, idx: number) => {
                                        let no: any = ''
                                        switch (idx) {
                                            case 0:
                                                no = <img src={gold} />
                                                break
                                            case 1:
                                                no = <img src={silver} />
                                                break
                                            case 2:
                                                no = <img src={copper} />
                                                break
                                            default:
                                                no = <div className={styles.no}>0{idx + 1}</div>
                                                break
                                        }
                                        return (
                                            <div className={styles.price_block}>
                                                {!!item?.price && (
                                                    <>
                                                        {no}
                                                        <div className={styles.name}>{item?.name || '--'}</div>
                                                        <div>
                                                            出价 <span>{item?.price || '-'}万</span>
                                                        </div>
                                                    </>
                                                )}
                                            </div>
                                        )
                                    }}
                                </AnimationList>
                            </div>
                            <div className={styles.people_num}>参拍剩余人数：{binding_info?.bidding_student_num || 0} 人</div>
                        </div>
                    </div>
                    <div className={success ? styles.auctioneer_success : styles.auctioneer} />
                    <div className={styles.explain_board}>
                        <div className={styles.title}>参拍商品{sortNum.split('')[lot_obj?.sort]}</div>
                        <div className={styles.content}>{lot_obj?.describe}</div>
                        {lot_obj?.is_last_lot === '0' && (
                            <HoverImage
                                className={styles.action_btn}
                                placeholderSrc={btn_chengjiao_n}
                                src={btn_chengjiao_s}
                                wait={500}
                                onClick={() => {
                                    if (!success) {
                                        audioRef.current?.play()
                                        setSuccess(true)
                                        send('step_flow', { params: { step: 5, lot_id: lot_obj.id } })
                                    }
                                }}
                            />
                        )}
                        {lot_obj?.is_last_lot === '1' && (
                            <HoverImage
                                className={styles.action_btn}
                                placeholderSrc={btn_over_n}
                                src={btn_over_s}
                                wait={500}
                                onClick={() => {
                                    if (!success) {
                                        audioRef.current?.play()
                                        setSuccess(true)
                                        send('step_flow', { params: { step: 6, lot_id: lot_obj.id } })
                                    }
                                }}
                            />
                        )}
                    </div>
                </div>
            </div>
            <audio ref={audioRef} src="https://cp-oss.busionline.com/qzsx/audio/价值观大拍卖音效4一锤定音.mp3" />
        </div>
    )
})
